﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TanWeb.Helpers;
using TanWeb.Models.Entities;
using TanWeb.Controllers.Business;
using System.Security.Cryptography;
using log4net;
using Newtonsoft.Json;
using System.Web.Routing;
using System.Collections;
using System.IO;
using System.Web.Script.Serialization;
using TanWeb.Models.Entities.Master;

namespace TanWeb.Controllers
{
    public class MasterController : Controller
    {
        //===============================================================
        //  プライベート変数
        //===============================================================
        #region Private Variable Declared    
        /// <summary>
        /// Log4net 変数
        /// </summary>
        protected static readonly ILog logger = LogManager.GetLogger(typeof(Controller));
        #endregion

        #region PAGE_LOGIN
        public ActionResult Index()
        {
            return View(Constants.PAGE_MASTER_LOGIN);
        }

        [RequiresRouteValues("user, password")]
        public ActionResult Login(string user, string password)
        {
            logger.Info("Start Controller: Master; Action: Login");

            try
            {
                if (user == string.Empty || password == string.Empty)
                {
                    return View(Constants.PAGE_MASTER_LOGIN);
                }

                MasterBusiness business = new MasterBusiness();
                string encryptedPassword = Utils.MD5Hash(password);

                if (!business.CheckLogin(user, encryptedPassword))
                {
                    return View(Constants.PAGE_MASTER_LOGIN);
                }
            }
            catch (Exception ex)
            {
                logger.Info("Error Controller: Master; Action: Login", ex);
            }

            logger.Info("End Controller: Master; Action: Login");

            return RedirectToAction("Main", new RouteValueDictionary( new 
                { pageIndex = 1, groupId = " ", subGroupId = " " }));
        }
        #endregion

        #region PAGE_MAIN
        [RequiresRouteValues("pageIndex, groupId, subGroupId")]
        public ActionResult Main(int pageIndex, string groupId, string subGroupId)
        {
            logger.Info("Start Controller: Master; Action: Main");

            if (!Utils.CheckLogin(logger))
            {
                return RedirectToAction("Index", Constants.CONTROLLER_MASTER_NAME);
            }

            Utils.SetSession(Constants.SESSION_UPLOADED_FILENAME, null);
            DetailBusiness business = new DetailBusiness();
            List<ItemGroup> listItemGroup = new List<ItemGroup>();
            List<SubItemGroup> listSubItemGroup = new List<SubItemGroup>();

            groupId = groupId == "0" ? "" : groupId.Trim();
            subGroupId = subGroupId == "0" ? "" : subGroupId.Trim();

            try
            {
                List<ProductProfile> lstProductProfile = business.GetProductInfo(groupId, subGroupId, 1);
                int pageCount = business.GetAllPageRecord(groupId, subGroupId);
                string[] nameInfo = business.GetNameInfo(groupId, subGroupId);
                Products products = new Products(pageCount, lstProductProfile, 1, groupId, nameInfo[0], subGroupId, nameInfo[1]);
                listItemGroup = business.GetAllItemGroup();
                if (groupId != string.Empty)
                {
                    listSubItemGroup = business.GetSubGroup(groupId);
                }
                Utils.SetSession(Constants.SS_LISTMENUITEM, listItemGroup);
                Utils.SetSession(Constants.SS_LISTSUBMENUITEM, listSubItemGroup);
                ViewBag.GroupId = groupId;
                ViewBag.SubGroupId = subGroupId;

                logger.Info("End Controller: Master; Action: Main");
                return View(Constants.PAGE_MASTER_MAIN, products);
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master; Action: Main", ex);
                return RedirectToAction("Index", Constants.CONTROLLER_MASTER_NAME);
            }
        }

        public string GetSubGroup(string itemGroupId)
        {
            logger.Info("Start Controller: Master - Action: GetSubGroup");

            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }

            DetailBusiness business = new DetailBusiness();
            List<SubItemGroup> lstSubGroup = new List<SubItemGroup>();

            try
            {
                lstSubGroup = business.GetSubGroup(itemGroupId);
                logger.Info("End Controller: Master - Action: GetSubGroup");
                return JsonConvert.SerializeObject(lstSubGroup);
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: GetSubGroup", ex);
            }

            return Constants.ERROR_PAGE;
        }

        [RequiresRouteValues("pageIndex, groupId, subGroupId")]
        public string GetListProducts(int pageIndex, string groupId, string subGroupId)
        {
            logger.Info("Start Controller: Master; Action: GetListProducts");

            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }

            DetailBusiness business = new DetailBusiness();
            string json = string.Empty;

            try
            {
                List<ProductProfile> lstProductProfile = business.GetProductInfo(groupId, subGroupId, pageIndex);
                int pageCount = business.GetAllPageRecord(groupId, subGroupId);

                foreach (ProductProfile product in lstProductProfile)
                {
                    product.ImageName = product.GetTempImagePath();
                }

                Products products = new Products(pageCount, lstProductProfile, pageIndex);
                json = JsonConvert.SerializeObject(products);
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master; Action: GetListProducts; ", ex);
                json = JsonConvert.SerializeObject(Constants.ERROR_PAGE);
            }

            return json;
        }

        [RequiresRouteValues("groupId, subGroupId, goBack")]
        public ActionResult New(string groupId, string subGroupId, string goBack)
        {
            logger.Info("Start Controller: Master; Action: New");

            if (!Utils.CheckLogin(logger))
            {
                return RedirectToAction("Index", Constants.CONTROLLER_MASTER_NAME);
            }

            ArrayList fileNameList = new ArrayList();
            Utils.SetSession(Constants.SESSION_UPLOADED_FILENAME, fileNameList);
            ViewBag.groupId = groupId;
            ViewBag.subGroupId = subGroupId;
            ViewBag.goBack = goBack;

            logger.Info("End Controller: Master; Action: New");

            return View(Constants.PAGE_MASTER_NEW);
        }

        /*[RequiresRouteValues("groupId, subGroupId, productId")]*/
        /*
        public ActionResult LoadAllThumnail(string groupId, string subGroupId, string productId)
        {
            logger.Info("Start Controller: Master; Action: LoadAllThumnail");

            if (!Utils.CheckLogin(logger))
            {
                return RedirectToAction("Index", Constants.CONTROLLER_MASTER_NAME);
            }

            MasterBusiness business = new MasterBusiness();

            try
            {
                List<string> listImageThumnail = business.GetAllImageThumnail(groupId, subGroupId, productId);
                ViewBag.ListThumnail = listImageThumnail;
                ViewBag.GroupId = groupId;
                ViewBag.SubGroupId = subGroupId;
                ViewBag.ProductId = productId;
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: LoadAllThumnail", ex);
            }

            logger.Info("End Controller: Master; Action: LoadAllThumnail");

            return View(Constants.PAGE_MASTER_IMAGE_PREVIEW);
        }
         * */


        public ActionResult LoadAllThumnail(string groupId, string subGroupId, string productId, string index)
        {
            logger.Info("Start Controller: Master; Action: LoadAllThumnail");

            /*
            if (!Utils.CheckLogin(logger))
            {
                return RedirectToAction("Index", Constants.CONTROLLER_MASTER_NAME);
            }
             * */

            MasterBusiness business = new MasterBusiness();

            try
            {
                List<string> listImageThumnail = business.GetAllImageThumnail(groupId, subGroupId, productId, index);
                ViewBag.ListThumnail = listImageThumnail;
                ViewBag.GroupId = groupId;
                ViewBag.SubGroupId = subGroupId;
                ViewBag.ProductId = productId;
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: LoadAllThumnail", ex);
            }

            logger.Info("End Controller: Master; Action: LoadAllThumnail");

            return View(Constants.PAGE_MASTER_IMAGE_PREVIEW);
        }

        /*[RequiresRouteValues("groupId, subGroupId, productId, imageIndex")]*/
        public string GetOriginalImageUrl(string groupId, string subGroupId, string productId, int imageIndex, string index)
        {
            logger.Info("Start Controller: Master; Action: GetOriginalImageUrl");

            /*
            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }
             * */

            MasterBusiness business = new MasterBusiness();
            string json = string.Empty;

            try
            {
                System.Drawing.Image image = business.GetImage(groupId, subGroupId, productId, imageIndex, index);
                json = Utils.GetImageUrl(image);
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: GetOriginalImageUrl", ex);
                json = Constants.ERROR_PAGE;
            }

            logger.Info("End Controller: Master; Action: GetOriginalImageUrl");

            return json;
        }

        #endregion

        #region PAGE_NEW

        [HttpPost]
        [AsyncTimeout(3600000)]
        public string Upload(HttpPostedFileBase file, string index)
        {
            logger.Info("Start Controller: Master; Action: Upload");

            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }

            string json = string.Empty;

            try
            {
                string path = Server.MapPath(Constants.PATH_UPLOAD_IMAGE);
                ArrayList fileNameList = (ArrayList) Utils.GetSession(Constants.SESSION_UPLOADED_FILENAME);

                string uploadFileName = Utils.SaveImage(file, path);
                string filePath = path + uploadFileName;
                if (uploadFileName != null && uploadFileName != string.Empty)
                {
                    System.Drawing.Image image = Utils.GetResizedImage(filePath);
                    string tempPath =  Server.MapPath(Constants.PATH_TEMP_IMAGE);
                    string tempFile = Utils.SaveImage(image, tempPath);
                    json += tempFile.Replace('\\', '/');
                    fileNameList.Add(new UploadedFile(index, uploadFileName));
                }

                Utils.SetSession(Constants.SESSION_UPLOADED_FILENAME, fileNameList);
                logger.Info("End Controller: Master; Action: Upload");
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master; Action: Upload; ", ex);
            }

            return json;
        }

        [HttpPost]
        public string Save()
        {
            logger.Info("Start Controller: Master - Action: Save");

            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }

            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            MasterBusiness business = new MasterBusiness();
            string json = string.Empty;

            try
            {
                string itemGroup = json_serializer.Deserialize<string>(Request["itemGroup"]);
                string subItemGroup = json_serializer.Deserialize<string>(Request["subItemGroup"]);
                List<UploadedProduct> products = json_serializer.Deserialize<List<UploadedProduct>>(Request["products"]);
                string date = DateTime.Now.ToString(Constants.FORMAT_FULL_DATE_TIME);

                foreach (UploadedProduct product in products)
                {
                    int productId = business.RegisterProduct(itemGroup, subItemGroup, product, date);

                    if (business.RegisterImage(itemGroup, subItemGroup, productId, product.index, date) == -1) 
                    {
                        json = Constants.ERROR_PAGE;
                        break;
                    }
                }

                logger.Info("End Controller: Master - Action: Save");

                if (json == string.Empty)
                {
                    json = Constants.PAGE_OK;
                }
            }
            catch (Exception ex)
            {
                json = Constants.ERROR_PAGE;
                logger.Error("Error Controller: Master - Action: Save", ex);
            }

            return JsonConvert.SerializeObject(json);
        }
        #endregion

        #region PAGE_UPDATE

        [RequiresRouteValues("groupId, subGroupId, productId, goBack")]
        public ActionResult Update(string groupId, string subGroupId, string productId, string goBack)
        {
            logger.Info("Start Controller: Master; Action: Update");

            if (!Utils.CheckLogin(logger))
            {
                return RedirectToAction("Index", Constants.CONTROLLER_MASTER_NAME);
            }

            MasterBusiness business = new MasterBusiness();
            Product product = new Product();
            ArrayList fileNameList = new ArrayList();
            Utils.SetSession(Constants.SESSION_UPLOADED_FILENAME, fileNameList);
            System.Drawing.Image image = null;

            try
            {
                product = business.GetProductInfo(groupId, subGroupId, productId);
                image = business.GetImage(groupId, subGroupId, productId, product.ImageId, null, Constants.TYPE_IMAGE_NORMAL);
                ViewBag.Image = Utils.GetImageUrl(image);
                ViewBag.GoBack = goBack;
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: Update", ex);
            }

            logger.Info("End Controller: Master; Action: Update");

            return View(Constants.PAGE_MASTER_UPDATE, product);
        }

        [RequiresRouteValues("data")]
        public string UpdateProduct(string data)
        {
            logger.Info("Start Controller: Master; Action: UpdateProduct");

            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }

            MasterBusiness business = new MasterBusiness();
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            Product product = json_serializer.Deserialize<Product>(data);
            string json = string.Empty;

            try
            {
                int result = business.UpdateProduct(product);
                json = Constants.PAGE_OK;
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: UpdateProduct", ex);
                json = Constants.ERROR_PAGE;
            }

            logger.Info("End Controller: Master; Action: UpdateProduct");

            return JsonConvert.SerializeObject(json);
        }

        [HttpPost]
        public string Delete() 
        {
            logger.Info("Start Controller: Master; Action: Delete");

            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }

            JavaScriptSerializer json_serializer = new JavaScriptSerializer();
            MasterBusiness business = new MasterBusiness();
            string json = string.Empty;

            try
            {
                List<string> lstId = json_serializer.Deserialize<List<string>>(Request["lstId"]);
                //int result = business.DeleteProducts(lstProductId);
                int result = business.DeleteProductsById(lstId);

                json = Constants.PAGE_OK;
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: Delete", ex);
                json = Constants.ERROR_PAGE;
            }

            logger.Info("End Controller: Master; Action: Delete");

            return JsonConvert.SerializeObject(json);
        }

        [RequiresRouteValues("groupId, subGroupId, productId")]
        public string Delete(string groupId, string subGroupId, string productId)
        {
            logger.Info("Start Controller: Master; Action: Delete");
            string json = string.Empty;

            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }

            MasterBusiness business = new MasterBusiness();

            try
            {
                int result = business.DeleteProduct(groupId, subGroupId, productId);
                
                json = Constants.PAGE_OK;
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: Delete", ex);
                json = Constants.ERROR_PAGE;
            }

            logger.Info("End Controller: Master; Action: Delete");

            return JsonConvert.SerializeObject(json);
        }

        #endregion

        #region "REGISTER MENU"

        public ActionResult NewGroup()
        {
            logger.Info("Start Controller: Master; Action: NewGroup");

            if (!Utils.CheckLogin(logger))
            {
                return View(Constants.PAGE_MASTER_LOGIN);
            }

            DetailBusiness business = new DetailBusiness();
            List<ItemGroup> listItemGroup = new List<ItemGroup>();
            List<SubItemGroup> listSubItemGroup = new List<SubItemGroup>();

            try
            {
                string goBack = Request["goBack"];
                listItemGroup = business.GetAllItemGroup();
                listSubItemGroup = business.GetSubGroup(null);
                Utils.SetSession(Constants.SS_LISTMENUITEM, listItemGroup);
                Utils.SetSession(Constants.SS_LISTSUBMENUITEM, listSubItemGroup);
                ViewBag.goBack = goBack;
             }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: NewGroup", ex);
            }

            logger.Info("End Controller: Master; Action: NewGroup");

            return View(Constants.PAGE_MASTER_NEW_GROUP);
        }

        public ActionResult ShowAddGroupPage()
        {
            logger.Info("Start Controller: Master; Action: ShowAddGroupPage");

            if (!Utils.CheckLogin(logger))
            {
                return View(Constants.PAGE_MASTER_LOGIN);
            }

            try
            {
                string mode = Request["modeType"];
                string parentGroup = Request["parentGroup"];
                ViewBag.Mode = mode;
                ViewBag.ParentGroup = parentGroup;
                ViewBag.GroupName = string.Empty;

                if (mode.Contains("Update"))
                {
                    string id = Request["subId"];
                    DetailBusiness business = new DetailBusiness();
                    SubItemGroup subGroup = business.GetSubGroupById(id);

                    ViewBag.Id = id;
                    ViewBag.GroupName = subGroup.SubGroupName;
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: ShowAddGroupPage", ex);
            }

            logger.Info("End Controller: Master; Action: ShowAddGroupPage");
            return View(Constants.PAGE_MASTER_ADD_GROUP);
        }

        [RequiresRouteValues("parentGroup, groupName, mode")]
        public string RegisterGroup(string parentGroup, string groupName, string mode)
        {
            logger.Info("Start Controller: Master; Action: RegisterGroup");

            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }

            MasterBusiness business = new MasterBusiness();
            DetailBusiness dtBusiness = new DetailBusiness();
            string result = Constants.PAGE_OK;

            try
            {
                result = business.RegisterGroup(groupName, parentGroup, mode);

                if (mode == Constants.NEW_GROUP)
                {
                    List<ItemGroup> listItemGroup = dtBusiness.GetAllItemGroup();
                    foreach (ItemGroup group in listItemGroup)
                    {
                        if (group.GroupName == groupName)
                        {
                            result = group.id.ToString();
                            break;
                        }
                    }
                }
                else if (mode == Constants.NEW_SUB_GROUP)
                {
                    List<SubItemGroup> listSubItemGroup = dtBusiness.GetSubGroup(parentGroup);
                    foreach (SubItemGroup group in listSubItemGroup)
                    {
                        if (group.SubGroupName == groupName)
                        {
                            result = group.id.ToString();
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: RegisterGroup", ex);
                result = Constants.ERROR_PAGE;
            }

            logger.Info("End Controller: Master; Action: RegisterGroup");
            return result;
        }



        [RequiresRouteValues("id, groupName, mode")]
        public string UpdateGroup(string id, string groupName, string mode)
        {
            logger.Info("Start Controller: Master; Action: UpdateGroup");

            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }

            MasterBusiness business = new MasterBusiness();
            DetailBusiness dtBusiness = new DetailBusiness();
            string result = Constants.PAGE_OK;

            try
            {
                if (mode == Constants.UPDATE_SUB_GROUP)
                {
                    SubItemGroup item = dtBusiness.GetSubGroupById(id);
                    business.RegisterGroup(groupName, id, mode);
                    result = id;
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: UpdateGroup", ex);
                result = Constants.ERROR_PAGE;
            }

            logger.Info("End Controller: Master; Action: UpdateGroup");
            return result;
        }

        public string DeleteSubGroup()
        {
            logger.Info("Start Controller: Master; Action: DeleteSubGroup");

            if (!Utils.CheckLogin(logger))
            {
                return Constants.LOST_SESSION;
            }

            MasterBusiness business = new MasterBusiness();
            string result = Constants.PAGE_OK;
            JavaScriptSerializer json_serializer = new JavaScriptSerializer();

            try
            {
                List<string> arrDel = json_serializer.Deserialize<List<string>>(Request["arrDel"]);
                result = business.DeleteSubGroup(arrDel);
                result = business.DeleteProductsBySubGroupId(arrDel).ToString();
            }
            catch (Exception ex)
            {
                logger.Error("Error Controller: Master - Action: DeleteSubGroup", ex);
                result = Constants.ERROR_PAGE;
            }

            logger.Info("End Controller: Master; Action: DeleteSubGroup");
            return JsonConvert.SerializeObject(result);
        }

        #endregion
    }
}